package com.meida.paotui.app.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.meida.common.base.handler.SmsSendHandler;
import com.meida.common.constants.CommonConstants;
import com.meida.common.constants.SettingConstant;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.GetModel;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.model.SaveModel;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.*;
import com.meida.module.admin.provider.service.BaseAccountService;
import com.meida.module.system.client.entity.SysHtml;
import com.meida.module.system.provider.service.impl.SysHtmlServiceImpl;
import com.meida.module.user.client.entity.AppAccount;
import com.meida.module.user.client.entity.AppUser;
import com.meida.module.user.provider.service.AppAccountService;
import com.meida.module.user.provider.service.AppUserService;
import com.meida.module.user.provider.service.impl.AppUserServiceImpl;
import com.meida.paotui.bus.client.entity.BusAppuser;
import com.meida.paotui.bus.client.entity.BusIdentity;
import com.meida.paotui.bus.client.entity.BusSett;
import com.meida.paotui.bus.client.entity.BusTradeDetail;
import com.meida.paotui.bus.provider.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


@Api(tags = "跑腿登陆模块")
@RestController
public class AccountController {

    @Autowired
    private AccountService accountService;
    @Autowired
    private BusIdentityService busidentityService;
    @Autowired
    private AppUserServiceImpl accountUserService;

    @Autowired
    private BusSettService bussettService;
    @Autowired
    private AppUserService userService;
    @Autowired
    private SysHtmlServiceImpl syshtml;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private AppAccountService appAccountService;
    @Autowired
    private BaseAccountService baseUserAccountService;
    @Autowired
    private BusTradeDetailService busTradeDetailService;
    @Autowired
    private BusAppuserService appuserService;






    private String OPEN_URL = "https://api.weixin.qq.com/sns/jscode2session?";
    private String APPID = "wx927cdef4ccc5b63b";
    private String SECRET = "16428b8e3df123af05adcb04836a5b4c";// 秘钥

    /**
     * 注册账户
     */
    @ApiOperation(value = "注册账户", notes = "注册会员账户")
    @PostMapping(value = "/login/registerAccount")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "accountName", value = "账户名", paramType = "form"),
        @ApiImplicitParam(name = "telephone", value = "手机号", paramType = "form"),
        @ApiImplicitParam(name = "userType", value = "用户类型", paramType = "form"),
        @ApiImplicitParam(name = "smsCode", value = "验证码", paramType = "form", defaultValue = "18739941307"),
        @ApiImplicitParam(name = "password", value = "密码(选填)", paramType = "form"),
        @ApiImplicitParam(name = "userName", value = "用户名(选填)", paramType = "form"),
        @ApiImplicitParam(name = "nickName", value = "昵称(选填)", paramType = "form"),
        @ApiImplicitParam(name = "cardNo", value = "身份证号码(选填)", paramType = "form"),
        @ApiImplicitParam(name = "cardNoImg", value = "身份证正面", paramType = "form"),
        @ApiImplicitParam(name = "cardNoImg2", value = "身份证反面", paramType = "form"),
        @ApiImplicitParam(name = "sex", value = "性别", paramType = "form")
    })
    public ResultBody registerAccount(SaveModel model,
                                      @RequestParam(value = "accountName", required = false) String accountName,
                                      @RequestParam(value = "telephone", required = false) String telephone,
                                      @RequestParam(value = "smsCode", required = false) String smsCode,
                                      @RequestParam(value = "userType", defaultValue = "USER") String userType,
                                      @RequestParam(value = "password", required = false, defaultValue = CommonConstants.DEF_PWD) String password,
                                      @RequestParam(value = "areaCode", required = false, defaultValue = "+86") String areaCode,
                                      @RequestParam(value = "userName", required = false) String userName,
                                      @RequestParam(value = "nickName", required = false) String nickName,
                                      @RequestParam(name = "cardNo", required = false) String cardNo,
                                      @RequestParam(name = "cardNoImg", required = false) String cardNoImg,
                                      @RequestParam(name = "cardNoImg2", required = false) String cardNoImg2,
                                      @RequestParam(name = "heathImg", required = false) String heathImg,
                                      @RequestParam(name = "sex", required = false) String sex
    ) {
        return accountService.registerAccount(model, accountName, telephone, areaCode, smsCode, userType, password, userName, nickName, cardNo, cardNoImg, cardNoImg2, heathImg,sex);
    }

    @ApiOperation(value = "获取验证码", notes = "useType说明:REG用于注册、绑定新手机号,UPDATE用户忘记密码,修改密码")
    @PostMapping(value ="/appuser/getpadCode")
    public ResultBody getpadCode(String useType, String mobile, @RequestParam(value="areaCode", defaultValue = "+86", required = false) String areaCode, String accountType) {
        EntityMap map = redisUtils.getConfigMap("SMS_CONFIG");
        Boolean encryption = map.get(SettingConstant.SMS_ENCRYPTION, false);
        String tel = mobile;
        if (FlymeUtils.isNotEmpty(encryption) && encryption) {
            //解密手机号
            tel = Des3Util.decode(mobile);
        }
        ApiAssert.isNotEmpty("验证码用途不能为空", useType);
        //手机号是否已注册
        Boolean tag = appAccountService.checkByAccountName(tel);
        Map<String, Object> params = new HashedMap();
        if (!tag) {
            return ResultBody.failed("账号不存在");
        }
        AppAccount account = appAccountService.getMobileAccount(tel);
        if (FlymeUtils.isNotEmpty(account)) {
            Long userId = account.getUserId();

            if (FlymeUtils.isNotEmpty(userId)) {
                Boolean check = appAccountService.isExist(userId, accountType);
                if (check) {
                    return ResultBody.failed("该账号已绑定");
                }
            }
        }
        Integer code = RandomUtil.randomInt(100000, 999999);
        //保存验证码
        redisUtils.set(CommonConstants.PRE_SMS + tel, code, 900);
        Boolean enable = map.get(SettingConstant.OPEN_SMS, false);
        if (enable) {
            params.put("code", code);
            String handlerName = map.get(SettingConstant.SMSCODE_HANDLER, "");
            //发送验证码
            SmsSendHandler smsSendHandler = SpringContextHolder.getHandler(handlerName, SmsSendHandler.class);
            smsSendHandler.sendSms(tel, "SMS_185240040", params);
            return ResultBody.msg("发送成功").data(params);
        }
        return  ResultBody.ok("发送成功").data(params);
    }
/**
     * 更新当前用户基本资料
     */
    @ApiOperation(value = "当前用户-更新", notes = "可更新单个字段")
    @PostMapping(value = "/appuser/appupdateMine")
    public ResultBody appupdateMine(@RequestParam("nickName") String nickName, @RequestParam("sex") String sex , @RequestParam("avatar") String avatar , @RequestParam("mobile") String mobile,@RequestParam("userName") String userName ) {
        EntityMap map =new EntityMap();
        if(ObjectUtils.isNotEmpty(nickName)) {
            map.put("nickName", nickName);
        }
        if(ObjectUtils.isNotEmpty(sex)) {
            map.put("sex", sex);
            QueryWrapper<BusIdentity> qw=new QueryWrapper();
            qw.eq("userId",OpenHelper.getUserId());
            BusIdentity identity = busidentityService.getOne(qw);
            if(FlymeUtils.isNotEmpty(identity)){
                identity.setSex(sex);
                busidentityService.saveOrUpdate(identity);
            }
        }
        if(ObjectUtils.isNotEmpty(userName)) {
            QueryWrapper<BusIdentity> qw=new QueryWrapper();
            qw.eq("userId",OpenHelper.getUserId());
            BusIdentity identity = busidentityService.getOne(qw);
            if(FlymeUtils.isNotEmpty(identity)){
                identity.setUserName(userName);
                busidentityService.saveOrUpdate(identity);
            }
        }
        if(ObjectUtils.isNotEmpty(avatar)) {
            map.put("avatar", avatar);
        }
        if(ObjectUtils.isNotEmpty(mobile)) {
            map.put("mobile", mobile);
        }
        return accountService.updateUser(OpenHelper.getUserId(),mobile,sex,nickName,userName,avatar);
    }
    @ApiOperation(
        value = "换绑手机号",
        notes = "换绑手机号"
    )
    @PostMapping(value = "/appuser/changeMobile")
    @ApiImplicitParams({@ApiImplicitParam(
        name = "mobile",
        required = true,
        value = "新手机号",
        paramType = "form",
        defaultValue = "17703715373"
    ), @ApiImplicitParam(
        name = "smsCode",
        required = true,
        value = "验证码",
        paramType = "form"
    )})
    public ResultBody<Boolean> changeMobile(@RequestParam("mobile") String mobile, @RequestParam("smsCode") String smsCode) {
        Long userId = OpenHelper.getUserId();
        ResultBody  b= accountService.changeMobile(userId, mobile, smsCode);
        System.out.println(b);
        return b;
    }



    /**
     * 获取当前用户详细信息
     *
     * @return
     */
    @ApiOperation(value = "我的-用户中心", notes = "可通过编写自定义handler方法扩展")
    @GetMapping(value = "/login/mineInfo1")
    public ResultBody getMineInfo(GetModel model) {
        EntityMap map =new EntityMap();
        ResultBody resultBody=accountUserService.getMineInfo(model);
        Long userid= OpenHelper.getUserId();
        ApiAssert.isNotEmpty("请先登录", userid);
        QueryWrapper<BusIdentity> qw=new QueryWrapper();
        qw.eq("userId",userid);
        BusIdentity identity= busidentityService.getOne(qw);
        if(FlymeUtils.isEmpty(identity)){
            map.put("type",0);
        }else{
            if(FlymeUtils.isNotEmpty(identity.getUserType())&&identity.getUserType().equals("3")){
                if(FlymeUtils.isEmpty(identity.getCardNoImg())||FlymeUtils.isEmpty(identity.getCardNoImg2())||FlymeUtils.isEmpty(identity.getCardNo())) {
                    map.put("type", 0);
                }else{
                    map.put("type",identity.getUserType());
                    map.put("ispass",identity.getIsPass());
                    map.put("codestatus",identity.getCodeStatus());
                }
            } else{
                map.put("type",identity.getUserType());
                map.put("ispass",identity.getIsPass());
                map.put("codestatus",identity.getCodeStatus());
            }
        }
        map.put("userInfo",resultBody.getData());
        QueryWrapper<BusSett> qw_1=new QueryWrapper();
        qw_1.eq("userId",userid);
        BusSett set=bussettService.getOne(qw_1);
        if(FlymeUtils.isNotEmpty(set)){
            map.put("setStatus",set.getStatus());
        }else{
            map.put("setStatus","1");
        }
        return  ResultBody.ok(map);
    }
    /**
     * 获取当前用户详细信息
     *
     * @return
     */
    @ApiOperation(value = "消息通知开关", notes = "消息通知开关")
    @PostMapping(value = "/user/setmessageStatus")
    public ResultBody setmessageStatus(String status) {
        EntityMap map =new EntityMap();
        Long userid= OpenHelper.getUserId();
        ApiAssert.isNotEmpty("请先登录", userid);
        QueryWrapper<BusSett> qw_1=new QueryWrapper();
        qw_1.eq("userId",userid);
        BusSett set=bussettService.getOne(qw_1);
        if(FlymeUtils.isEmpty(set)){
            BusSett sets=new BusSett();
            sets.setUserId(userid);
            sets.setStatus(status);
            bussettService.save(sets);
        }else{
            set.setStatus(status);
            bussettService.saveOrUpdate(set);
        }
        return  ResultBody.ok();
    }

    @ApiOperation(value = "通过手机号判断用户是否存在", notes = "校验用户")
    @PostMapping(value = "/user/getuserbyTel")
    public ResultBody getuserInfo(String mobile) {
        EntityMap map =new EntityMap();
        AppUser appUser = userService.getUserByMobile(mobile);
        if(FlymeUtils.isEmpty(appUser)){
            map.put("ifetxt","0");
        }else{
            map.put("ifetxt","1");
        }
        return  ResultBody.ok(map);
    }

    @ApiOperation(value = "绑定成功以后插入扩展表", notes = "绑定成功以后插入扩展表")
    @PostMapping(value = "/user/setuserType")
    public ResultBody setuserType(String userType) {
        OpenHelper.getUserId();
        BusAppuser user=new  BusAppuser();
        user.setUserId(OpenHelper.getUserId());
        user.setSysUserType(userType);
        appuserService.save(user);
        return  ResultBody.ok();
    }
    @ApiOperation(value = "获取提现银行卡号", notes = "获取提现银行卡号")
    @PostMapping(value = "/user/getbankNo")
    public ResultBody getbankNo( ) {
        EntityMap map =new EntityMap();
        AppUser user= userService.getById(OpenHelper.getUserId());
        if(FlymeUtils.isEmpty(user)) {
            return ResultBody.failed("重新登录");
        }
        QueryWrapper<BusTradeDetail>  qw= new QueryWrapper();
        qw.eq("userId",OpenHelper.getUserId());
        qw.orderByDesc("createTime");
        List<BusTradeDetail> entity=busTradeDetailService.list(qw);
        if(FlymeUtils.isNotEmpty(entity)){
            map.put("bankMsg",entity.get(0));
        }else{
            map.put("bankMsg",new Object());
        }
        return  ResultBody.ok(map);
    }
    @ApiOperation(value = "个人认证", notes = "添加实名认证表")
    @PostMapping(value = "/identity/save_identity")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "userName", value = "真实姓名", paramType = "form"),
        @ApiImplicitParam(name = "cardNo", value = "身份证号", paramType = "form"),
        @ApiImplicitParam(name = "cardNoImg", value = "身份证正面", paramType = "form"),
        @ApiImplicitParam(name = "cardNoImg2", value = "身份证反面", paramType = "form"),
        @ApiImplicitParam(name = "heathImg", value = "健康证正面", paramType = "form")
    })
    public ResultBody save_identity(@ModelAttribute(value = "updateModel") SaveModel saveModel,
                                    @RequestParam(value = "userId", required=false) String userId,
                                    @RequestParam(value = "userName", required=false) String userName,
                                    @RequestParam(value = "cardNo", required=false) String cardNo ,
                                    @RequestParam(value = "cardNoImg", required=false) String cardNoImg ,
                                    @RequestParam(value = "cardNoImg2", required=false) String cardNoImg2,
                                    @RequestParam(value = "userType", defaultValue = "1") String userType,
                                    @RequestParam(value = "heathImg", required=false) String heathImg,
                                    ResultBody resultBody
    ) {
        AppUser user= userService.getById(OpenHelper.getUserId());

        BusIdentity busIdentity=new BusIdentity();
        QueryWrapper<BusIdentity> identiy_qw=new QueryWrapper();
        identiy_qw.eq("userId",OpenHelper.getUserId());
        busIdentity=busidentityService.getOne(identiy_qw);
        if(FlymeUtils.isNotEmpty(user)&&FlymeUtils.isNotEmpty(user.getSex())){
            if(FlymeUtils.isEmpty(busIdentity)) {
                busIdentity = busidentityService.save(userName, user.getSex(), cardNo, cardNoImg, cardNoImg2, userType, heathImg);
            }else{
                busIdentity.setUserName(userName);
                busIdentity.setSex(String.valueOf(user.getSex()));
                busIdentity.setCardNo(cardNo);
                busIdentity.setCardNoImg(cardNoImg);
                busIdentity.setIsPass(2);
                busIdentity.setCardNoImg2(cardNoImg2);
                busIdentity.setUserType(userType);
                busIdentity.setHeathImg(heathImg);
                busIdentity.setCodeStatus("1");
                busidentityService.saveOrUpdate(busIdentity);
            }
        }else{
            //未知
            if(FlymeUtils.isEmpty(busIdentity)) {
                busIdentity = busidentityService.save(userName, 3, cardNo, cardNoImg, cardNoImg2, userType, heathImg);
            }else{
                busIdentity.setUserName(userName);
                busIdentity.setSex("3");
                busIdentity.setCardNo(cardNo);
                busIdentity.setCardNoImg(cardNoImg);
                busIdentity.setIsPass(2);
                busIdentity.setUserType(userType);
                busIdentity.setCodeStatus("1");
                busIdentity.setCardNoImg2(cardNoImg2);
                busIdentity.setHeathImg(heathImg);
                busidentityService.saveOrUpdate(busIdentity);
            }
        }
        if(FlymeUtils.isNotEmpty(user)){
            user.setUserName(userName);
            userService.saveOrUpdate(user);
        }
        resultBody.put("identity",busIdentity);
        return  resultBody;
    }

    @ApiOperation(value = "商家认证", notes = "添加实名认证表")
    @PostMapping(value = "/identity/saveComany")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "userName", value = "真实姓名", paramType = "form"),
        @ApiImplicitParam(name = "shopName", value = "商户名称", paramType = "form"),
        @ApiImplicitParam(name = "license", value = "营业执照", paramType = "form"),
        @ApiImplicitParam(name = "overdoor", value = "门头照", paramType = "form")
    })
    public ResultBody saveComany(@ModelAttribute(value = "updateModel") SaveModel saveModel,
                                 @RequestParam(value = "userId", required=false) String userId,
                                 @RequestParam(value = "userName", required=false) String userName,
                                 @RequestParam(value = "shopName", required=false) String shopName ,
                                 @RequestParam(value = "license", required=false) String license ,
                                 @RequestParam(value = "overdoor", required=false) String overdoor,
                                 @RequestParam(value = "userType", defaultValue = "2") String userType
    )
    {
        AppUser user= userService.getById(OpenHelper.getUserId());
        BusIdentity busIdentity=new BusIdentity();
        if(FlymeUtils.isNotEmpty(user)&&FlymeUtils.isNotEmpty(user.getSex())){
           busIdentity=busidentityService.saveidentity(userName,user.getSex(),shopName,license,overdoor,userType);
        }else{
            //未知
           busIdentity=busidentityService.saveidentity(userName,3,shopName,license,overdoor,userType);
        }
        if(FlymeUtils.isNotEmpty(user)){
            user.setUserName(userName);
            userService.saveOrUpdate(user);
        }
        return ResultBody.ok(busIdentity);
    }


    @ApiOperation(value = "html", notes = "协议详情")
    @PostMapping(value = "/html/gethtmlBycode")
    public ResultBody gethtml(String htmlCode)
    {
        if(FlymeUtils.isEmpty(htmlCode)){
            ResultBody.failed("htmlCode参数不能为空");
        }
        SysHtml html= syshtml.findByCode(htmlCode);
        return ResultBody.ok(html);
    }

    @ApiOperation(value = "设置发件验证码开关", notes = "设置发件验证码开关")
    @PostMapping(value = "/user/setcodeStatus")
    public ResultBody setcodeStatus(String status)
    {
       Long userId=OpenHelper.getUserId();
       if(FlymeUtils.isNotEmpty(userId)){
           QueryWrapper<BusIdentity> qw=new QueryWrapper<>();
           qw.eq("userId",userId);
          BusIdentity identity=busidentityService.getOne(qw);
        //商家用户且审核通过可以操作此按钮
           if(FlymeUtils.isNotEmpty(identity)){
               if(identity.getUserType().equals("2")&&identity.getIsPass()==1){
                   identity.setCodeStatus(status);
                   busidentityService.saveOrUpdate(identity);
               }else{
                   return  ResultBody.failed("您身份认证未审核通过");
               }
           }else{
               return ResultBody.failed("您还未进行身份认证");
           }
       }else{
           return  ResultBody.failed("请重新登陆");
       }
        return ResultBody.ok();
    }


    @ApiOperation(value = "初始化认证接口", notes = "初始化认证接口")
    @PostMapping(value = "/user/getIdentity")
    public ResultBody getIdentity(String userType) {
        Long userId = OpenHelper.getUserId();
        BusIdentity identity=new BusIdentity();
        if (FlymeUtils.isNotEmpty(userId)) {
            QueryWrapper<BusIdentity> qw = new QueryWrapper<>();
            qw.eq("userId", userId);
            qw.eq("userType", userType);
            identity = busidentityService.getOne(qw);
        }else{
            return ResultBody.failed("请重新登陆");
        }
        return ResultBody.ok(identity);

    }
    /**
     * 重置账户密码
     */
    @ApiOperation(value = "账户-重置账户密码", notes = "重置账户密码")
    @PostMapping("/pwd/changePwd")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "password", value = "新密码", paramType = "form")
    })
    public ResultBody changePwd(@RequestParam(value = "password", required = false) String password,@RequestParam(value = "oldPassword", required = false) String oldPassword
    ) {
        Long userId=OpenHelper.getUserId();
         baseUserAccountService.resetPassword(userId,password);
        return ResultBody.msg("密码重置成功");
    }
    /**
     * 微信小程序登录，获取openid
     */
    @RequestMapping(value = "/thirdlogin")
    public void login(ResultBody resultBody, String code) {
        ResultBody j = new ResultBody();
        if (ObjectUtils.isEmpty(code)) {
            ResultBody.failed("code不能为空");
        } else {

                String url = OPEN_URL + "appid=" + APPID + "&secret=" + SECRET + "&js_code=" + code
                    + "&grant_type=authorization_code";


/*                CriterionMap map = JsonUtil.jsonToCriterionMap(json);
                String openId = map.getString("openid");
                String sessionKey = map.getString("session_key");
                // 根据openId查询用户是否存在，不存在就保存，若存在就不保存但要返回用户ID
                Account account = accountService.findbyAccountopenId(openId);
                CriterionMap newmap = JsonUtil.jsonToCriterionMap(json);
                if (ObjectUtils.isEmpty(account)) {
                    Account newaccount = new Account();
                    newaccount.setOpenId(openId);
                    newaccount.setAccountType(AccountTypeEnum.App_WX.text);
                    accountService.insert(newaccount);
                    String token = jwtUtils.generateToken(newaccount.getId());
                    AccountInfo accountInfo = new AccountInfo();
                    accountInfo.setId(newaccount.getId());
                    accountInfoService.insert(accountInfo);
                    newmap.put("token", token);
                } else {
                    accountService.saveOrUpdate(account);
                    newmap.put("token", jwtUtils.generateToken(account.getId()));
                }
                j.setObject(newmap);
            } catch (Exception e) {
                j.setError("服务器异常");
            }
        }
        JsonUtil.writeObj(response, j);*/
            }
            }

    }




